package com.itheima.work;

import com.itheima.domain.Product;
import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

/**
 * @author Zhang_Han
 * @version 1.0
 * @date 2020/7/19 19:39
 */

@SuppressWarnings("all")
public class Demo_Work_001 {
    public static void main(String[] args) throws Exception {
        /*要求：
         * 写java程序解析上面的配置文件
         * 将每一个product信息封装成Product对象
         * 将多个Product对象存储到List集合中
         */
        //创建解析器对象;
        SAXReader sr = new SAXReader();
        //加载文件;
        Document document = sr.read(new File("demo_xml\\xml\\products.xml"));
        //获取根标签 ;
        Element rootElement = document.getRootElement();
        //获取跟标签下面的所有子标签
        List<Element> elements = rootElement.elements("product");

        //创建一个存放数据的集合 ;
        ArrayList<Product> list = new ArrayList<>();

        //遍历集合 ;
        for (Element element : elements) {
            Attribute idElement = element.attribute("id");
            String id = idElement.getValue();
            String name = element.elementText("name");
            String price = element.elementText("price");
            String color = element.elementText("color");
            String storageMemory = element.elementText("storageMemory");
            String runningMemory = element.elementText("runningMemory");
            //进行数据封装;
            Product p = new Product(Integer.parseInt(id),
                    name, Double.parseDouble(price),
                    color, storageMemory, runningMemory);

            //将数据添加到集合当中;
            list.add(p);
        }

        for (Product product : list) {
            System.out.println(product);
        }
    }
}
